package com.ybu.service.impl;

import com.ybu.common.*;
import com.ybu.mapper.UserMapper;
import com.ybu.pojo.dto.UserInfoDTO;
import com.ybu.pojo.dto.UserLoginDTO;
import com.ybu.pojo.dto.UpdatePwdDTO;
import com.ybu.pojo.entity.User;
import com.ybu.pojo.dto.RegisterDTO;
import com.ybu.pojo.vo.UserLoginVO;
import com.ybu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@Service //业务层
@Slf4j
@Transactional //事务
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(RegisterDTO registerDTO) {
//判断密码与重复密码是否一致
        if (!registerDTO.getPassword().equals(registerDTO.getRePassword())) {
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "两次输入的密码不一致");
        }
//生成salt
        String salt = UUID.randomUUID().toString().replace("-", "");
// 对密码进行加密
        String password = MD5Utils.enctype(registerDTO.getPassword(), salt, Constants.HASH_TIME);
        log.debug("密码加密后：{}", password);
        log.debug("salt：{}", salt);
//封装user
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(password);
        user.setSalt(salt);
        user.setIsDelete(Constants.IS_NOT_DELETE);
        user.setCreatedUser(registerDTO.getUsername());
//调用持久层进行新增用户
        int result = userMapper.insert(user);
        if (result != 1) {
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "注册用户失败");
        }
    }

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //根据用户名去查询用户
        User user = userMapper.getByName(userLoginDTO.getUsername());
        if (user == null || user.getUsername() == null) {
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "登录的用户名不存在");
        }
        //判断是否被锁定
        if (user.getIsDelete() == 1) {
            throw new ServiceException(ServiceCode.ERR_FORBIDDEN, "该账户被锁定");
        }
        //判断密码
        //将登录密码进行加密
        String password = MD5Utils.enctype(userLoginDTO.getPassword(), user.getSalt(), Constants.HASH_TIME);
        if (!password.equals(user.getPassword())) {
            throw new ServiceException(ServiceCode.ERR_FORBIDDEN, "密码错误");
        }
        // 用户登录成功，保证逻辑的粒度
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setUsername(user.getUsername());
        //生成token
        String token = JwtUtils.generateToken(userLoginVO);
        userLoginVO.setToken(token);
        return userLoginVO;
    }


    @Override
    public void updatePwd(UpdatePwdDTO updatePwdDTO, UserLoginVO userLoginVO) {
        if (!updatePwdDTO.getNewPwd().equals(updatePwdDTO.getReNewPwd())) {
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "两次输入的密码不一致");
        }
/*判断原来密码
根据登录用户的身份（username），去查询数据库，得到一个用户对象，判断密码
*/
        User user = userMapper.getByName(userLoginVO.getUsername());
//将原来密码加密
        String password = MD5Utils.enctype(updatePwdDTO.getOldPwd(), user.getSalt(), Constants.HASH_TIME);
        if (!password.equals(user.getPassword())) {
            throw new ServiceException(ServiceCode.ERR_FORBIDDEN, "没有权限修改密码");
        }
//旧密码与数据库的密码匹配上
//获取盐值
        String salt = UUID.randomUUID().toString().replace("-", "");
//重新加密
        String newPwd = MD5Utils.enctype(updatePwdDTO.getNewPwd(), salt, Constants.HASH_TIME);
//构建用户信息
        new User();
        user.setPassword(newPwd);
        user.setSalt(salt);
        user.setModifiedUser(userLoginVO.getUsername());
//封装修改条件
        user.setId(userLoginVO.getId());
//修改
        int result = userMapper.updatePwd(user);
        if (result != 1) {
            throw new ServiceException(ServiceCode.ERR_UPDATE_FAILED, "修改密码失败");
        }
    }
    @Override
    public void editInfo(UserInfoDTO userInfoDTO, UserLoginVO userLoginVO){

        User user = new User();
        user.setUsername(userLoginVO.getUsername());
        user.setGender(userInfoDTO.getGender());
        user.setPhone(userInfoDTO.getPhone());
        user.setEmail(userInfoDTO.getEmail());
        //封装修改条件
        user.setId(userLoginVO.getId());
        user.setModifiedUser(userLoginVO.getUsername());
        int result = userMapper.editInfo(user);
        if(result !=1)
        {
            throw new ServiceException(ServiceCode.ERR_UPDATE_FAILED,"修改个人资料失败" );

        }


    }

    @Override
    public void updateAvatar(MultipartFile avatar, UserLoginVO userLoginVO)  {
//文件上传的路径
        String path = System.getProperty("user.dir")+ File.pathSeparatorChar+"src"+File.separator+"main"+
                File.separator+"resources"+File.separator+"images";
        String filename=avatar.getOriginalFilename();
//        拼接新的名称
        filename=UUID.randomUUID().toString().replace("-","")
                +filename.substring(filename.lastIndexOf("."));
        String fileExtension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase(); // 提取扩展名并转为小写

        List<String> allowedExtensions = Arrays.asList("jpg", "jpeg", "png", "gif");

        if (!allowedExtensions.contains(fileExtension)) {
            throw new IllegalArgumentException("Invalid file type. Only JPG, JPEG, PNG, GIF are allowed.");
        }
        long fileSize = avatar.getSize();
        long maxSize = 1024 * 1024; // 1MB
        if (fileSize > maxSize) {
            throw new IllegalArgumentException("File size exceeds the maximum allowed limit.");
        }

//        创建父目录
        String savePath = null;
        File parentFile = new File(savePath,filename);
//        上传文件
        try {
//上传文件
            avatar.transferTo(parentFile);
        } catch (IOException e) {
            log.debug(e.getMessage());
            throw new ServiceException(ServiceCode.ERR_FILE_UPLOAD,"文件上传失败");
        }

        User user = new User();
        user.setModifiedUser(userLoginVO.getUsername());
        user.setId(userLoginVO.getId());
        user.setAvatar(filename);
//        int result = userMapper.updateAvatar(user);
        int result=userMapper.setAvatar(user);
        if (result != 1) {
            boolean delete = parentFile.delete();
            if(!delete){
                log.debug("头像上传失败，需删除头像",filename);
            }

            throw new ServiceException(ServiceCode.ERR_UPDATE_FAILED, "修改头像失败");
        }
    }



}




